﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Windows;
using System.Windows.Controls;

namespace ImageUploaderComponent.Data
{

    [DataContract]
    public class UploaderViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private bool permissionWarningShown;
        public UploaderViewModel()
        {
            ImageDataList = new ObservableCollection<ImageDataViewModel>();
            ImageDataList.CollectionChanged += imageDataListCollectionChanged;
        }

        public UploaderViewModel(ObservableCollection<ImageDataViewModel> fileList)
        {
            ImageDataList = fileList;
        }

        private ObservableCollection<ImageDataViewModel> imageDataList;
        [DataMember]
        public ObservableCollection<ImageDataViewModel> ImageDataList
        {
            get { return imageDataList; }
            set
            {
                imageDataList = value;
                changeProperty("ImageDataList");
            }
        }

        private ObservableCollection<MediaviewModelBase> demoDataList;
        [DataMember]
        public ObservableCollection<MediaviewModelBase> DemoDataList
        {
            get { return demoDataList; }
            set
            {
                demoDataList = value;
                changeProperty("DemoDataList");
            }
        }

        [DataMember]
        public string SkillId { get; set; }

        [DataMember]
        public int SkillKeyId { get; set; }

        [DataMember]
        public string ClientId { get; set; }

        [DataMember]
        public string SkillName { get; set; }

        [DataMember]
        public int UserId { get; set; }

        private bool isUploading;
        public bool IsUploading
        {
            get { return isUploading; }
            private set
            {
                isUploading = value;
                changeProperty("IsUploading");
            }
        }

        private readonly Dictionary<Guid, DataGridRow> currentlyUploadingRows = new Dictionary<Guid, DataGridRow>();


        public UploadStatus UploadFile(FileInfo file)
        {
            MediaviewModelBase model = new ImageDataViewModel(file);
            UploadStatus uploadStatus = model.validateMedia();
            if (uploadStatus == UploadStatus.InvalidExtension)
            {
                model.Status = UploadStatus.InvalidExtension;
                imageDataList.Add((ImageDataViewModel)model);
            }
            if (uploadStatus != UploadStatus.ValidUploadAttempt) return uploadStatus;
            replaceSameFileNameIfNecessary(model);
            model.IsUploading = true;
            model.Status = UploadStatus.Started;
            currentlyUploadingRows.Add(model.Key, null);
            ImageDataList.Add((ImageDataViewModel)model);
            //            data.IsDeletable = true;
            IsUploading = true;
            var service = new DataStorageMediator();
            service.BeginUploadFile(model.DataItem, UploadProgessChanged, uploadComplete);
            return UploadStatus.ValidUploadAttempt;
        }

        private void replaceSameFileNameIfNecessary(MediaviewModelBase model)
        {
            var modelWithSameFileName = ImageDataList.Where(m => m.FileName == model.FileName).FirstOrDefault();
            if (modelWithSameFileName != null)
            {
                ImageDataList.Remove(modelWithSameFileName);
            }
        }

        private void UploadProgessChanged(Guid key, double progress)
        {
            var data = currentlyUploadingRows.Where(i => i.Key == key).FirstOrDefault();
            MediaviewModelBase model = (MediaviewModelBase)data.Value.DataContext;
            model.Progress = progress;
        }

        private void uploadComplete(Guid dataKey, ResultStruct status)
        {
            lock (currentlyUploadingRows)
            {
                var data = currentlyUploadingRows.Where(i => i.Key == dataKey).FirstOrDefault();
                MediaviewModelBase model = (MediaviewModelBase)data.Value.DataContext;
                model.IsUploading = false;
                model.Status = status.Status;
                currentlyUploadingRows.Remove(model.Key);
                if (currentlyUploadingRows.Count == 0)
                {
                    IsUploading = false;
                }
            }

        }

        public void UploadingRowRecieved(DataGridRow row)
        {
            lock (currentlyUploadingRows)
            {
                var data = row.DataContext as ImageDataViewModel;
                if (data != null)
                {
                    if (currentlyUploadingRows.ContainsKey(data.Key))
                    {
                        currentlyUploadingRows[data.Key] = row;
                    }
                }
            }
        }

        public void SaveState()
        {
            var service = new DataStorageMediator();
            service.CommitImageMetaData(this, SkillKeyId);
        }

        public override string ToString()
        {
            string result = "";
            foreach (ImageDataViewModel imageData in ImageDataList)
            {
                result += imageData.FileName + Environment.NewLine;
            }
            return result;
        }



        private void imageDataListCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            changeProperty("ImageDataList");
        }

        private void changeProperty(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }


        public void DeleteOrArchive(ImageDataViewModel item)
        {
            if (item != null)
            {
                var itemToDelete = ImageDataList.Where(i => i.FileName == item.FileName).FirstOrDefault();
                ImageDataList.Remove(itemToDelete);
                var service = new DataStorageMediator();
                if (itemToDelete != null)
                    if (itemToDelete.IsDeletable)
                    {
                        service.DeleteFile(item);
                    }
                    else
                    {
                        service.ArchiveItem(item);
                    }
            }
        }

        public void attemptUpload(IEnumerable<FileInfo> fileInfo)
        {
            if (!permissionWarningShown)
            {
                permissionWarningShown = true;
                MessageBoxResult permissionResult = MessageBox.Show("By clicking OK, I certify that I have legal permission to upload the files that I am about to upload.", "Nursing Skills", MessageBoxButton.OKCancel);
                if (permissionResult == MessageBoxResult.Cancel)
                {
                    Application.Current.RootVisual.Visibility = Visibility.Collapsed;
                    return;
                }
            }
            foreach (var info in fileInfo)
            {

                UploadStatus status = UploadFile(info);

            }
        }

        public  OpenFileDialog GetDialog()
        {
            var dlg = new OpenFileDialog
            {
                Multiselect = true,
                Filter =
                    "Images (*.png;*.gif;*.jpg)|*.png;*.gif;*.jpg | All files (*.*)|*.*"
            };
            return dlg;
        }
    }

}
